package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /*
     * 计算营业额方法
     *  参数：开始日期begin，结束日期end
     *  查询order订单表中 状态是 已完成的，并且日期符合的订单，计算这些订单的总金额
     * */
    @Override

    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1. 构建TurnoverReportVO类中的 'dateList' 变量
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // 从begin开始，到end结束，每次加一天，循环条件是begin < end
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //2. 构建TurnoverReportVO类中的 'turnoverList' 变量
        // 计算每天的营业额
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 查询date日期的营业额，营业额就是某个日期，状态为已完成的订单的总金额
            // 获取当天日期最早时间和最晚时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN); // 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX); // 23:59:59
            // 构建一个MAP集合用于封装查询条件
            HashMap<Object, Object> conditionMap = new HashMap<>();
            conditionMap.put("begin", beginTime);
            conditionMap.put("end", endTime);
            conditionMap.put("status", Orders.COMPLETED); // 订单已完成状态
            Double turnover = orderMapper.sumByMap(conditionMap); // 在mapper层中"sumByMap"方法计算营业额
            turnoverList.add(turnover == null ? 0.0 : turnover); // 如果为null，则当天营业额设置为0.0
        }
        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /*统计用户数量方法*/
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 构建UserReportVO 对象的3个属性 分别是 dateList、totalUserList、newUserList
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // 将begin 到end之间，每隔一天，添加到dateList集合中
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);// begin 后移
        }
        // 构建总用户数和新增用户数的集合
        ArrayList<Integer> totalUserList = new ArrayList<>();
        ArrayList<Integer> newUserList = new ArrayList<>();
        // 遍历dateList集合，获取每个日期对应的用户数量
        for (LocalDate date : dateList) {
            // 获取当天日期最早时间和最晚时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap<Object, Object> conditionMap = new HashMap<>();
            // 1. 先查询总用户数
            conditionMap.put("end", endTime);
            Integer totalUser = userMapper.countByMap(conditionMap);
            // 2. 再查询新增用户数
            conditionMap.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(conditionMap);
            // 3. 添加到集合中
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        // 将集合封装到UserReportVO对象中
        return UserReportVO.builder().dateList(StringUtils.join(dateList, ",")).totalUserList(StringUtils.join(totalUserList, ",")).newUserList(StringUtils.join(newUserList, ",")).build();
    }

    /*订单统计相关方法*/
    @Override
    public OrderReportVO getrOdersStatistics(LocalDate begin, LocalDate end) {
        // 创建OrderReportVO对象的属性
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // 获取begin - end 之间的所有日期
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        // 创建每天订单量集合与每天有效订单量集合
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        // 遍历日期集合，获取每天的订单量与有效订单量
        for (LocalDate localDate : dateList) {
            // 获取当天日期的最早时间与最晚时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 创建条件查询
            Integer orderCount = getOrderConut(null, beginTime, endTime); // 订单总数
            Integer validOrderCount = getOrderConut(Orders.COMPLETED, beginTime, endTime); // 有效订单总数
            // 将结果分别封装进集合中
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        // 计算订单完成率
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount / totalOrderCount.doubleValue();
        }
        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ",")).orderCountList(StringUtils.join(orderCountList, ",")).validOrderCountList(StringUtils.join(validOrderCountList, ",")).build();
    }

    /*统计TOP10商品方法*/
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);

        // 调用Mapper层获取前10商品名称
        ArrayList<GoodsSalesDTO> saleTop10 = new ArrayList<>();
        saleTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        // 构建商品名集合
        ArrayList<String> names = (ArrayList<String>) saleTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        // 构建销量集合
        ArrayList<Integer> numbers = (ArrayList<Integer>) saleTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        // 返回结果
        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }

    private Integer getOrderConut(Integer status, LocalDateTime beginTime, LocalDateTime endTime) {
        // 调用OrderMapper 查询orders表
        HashMap<Object, Object> conditionMap = new HashMap<>();
        conditionMap.put("status", status);
        conditionMap.put("begin", beginTime);
        conditionMap.put("end", endTime);
        return orderMapper.countByMap(conditionMap);
    }
}
